﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace LP580.CG
{
    /// <summary>
    /// clsUserAccount 的摘要说明
    /// <summary>
    public class clsUserAccount
    {
        private static readonly string _CkValidKey = "uv";

        #region 构造函数

        public clsUserAccount() { }

        public clsUserAccount(int prmUserID)
        {
            clsUserAccount entity = clsUserAccount.GetByKey(prmUserID);
            this._userid = entity._userid;
            this._username = entity._username;
            this._userpass = entity._userpass;
            this._usermail = entity._usermail;
            this._membertype = entity._membertype;
            this._adddate = entity._adddate;
            this._lastlogin = entity._lastlogin;
            this._lastip = entity._lastip;
            this._logintimes = entity._logintimes;
            this._userdisable = entity._userdisable;
            this._expiredate = entity._expiredate;
        }

        #endregion

        /// <summary>
        /// 用户登陆验证
        /// </summary>
        /// <returns></returns>
        public static bool ValidUserLogin(string name, string pass)
        {
            return (ValidUser(name, pass) != null);
        }

        /// <summary>
        /// 验证用户
        /// </summary>
        /// <returns>成功返回ID值，否则为0</returns>
        public static clsUserAccount ValidUser(string name, string pass)
        {
            clsUserAccount user = null;
            if (name != "" && pass != "")
            {
                string sql = string.Format("SELECT UserID FROM [tbl_UserAccount] WHERE UserName='{0}' AND [UserPass] = '{1}'", name, pass);
                DBase dbo = new DBase();
                System.Data.IDataReader dr = dbo.ExecuteReader(sql);
                if (dr.Read())
                {
                    user = clsUserAccount.GetByKey(Convert.ToInt32(dr[0]));
                }
                dr.Dispose();
                dr = null;
                dbo.CloseConn();
                dbo = null;
            }
            return user;
        }

        /// <summary>
        /// 用户名是否存在
        /// </summary>
        /// <returns></returns>
        public static bool ExistUsername(string name)
        {
            bool rv = true;
            if (name != "")
            {
                string sql = string.Format("SELECT UserID FROM [tbl_UserAccount] WHERE UserName='{0}'", name);
                DBase dbo = new DBase();
                System.Data.IDataReader dr = dbo.ExecuteReader(sql);
                rv = dr.Read();
                dr.Dispose();
                dr = null;
                dbo.CloseConn();
                dbo = null;
            }
            return rv;
        }

        /// <summary>
        /// 处理用户登入
        /// </summary>
        public static void doUserLogin(clsUserAccount ua)
        {
            DataTableManage SaveDTM = new DataTableManage();
            string sql;
            sql = "UPDATE [tbl_UserAccount] SET " +
                "[LastLogin] = @LastLogin, " +
                "[LastIP] = @LastIP, " +
                "[LoginTimes] = [LoginTimes]+1 " +
            " WHERE UserID=@UserID";
            SaveDTM.Sql = sql;
            SaveDTM.AddNewParam("@LastLogin", DateTime.Now);
            SaveDTM.AddNewParam("@LastIP", System.Web.HttpContext.Current.Request.UserHostAddress);
            SaveDTM.AddNewParam("@UserID", ua._userid);
            SaveDTM.Update();
            clsUserAccount.setUserLoginCookie(ua);
        }

        /// <summary>
        /// 处理用户登出
        /// </summary>
        public static void doUserLogout()
        {
            if (HttpContext.Current.Request.Cookies[clsUserAccount._CkValidKey] != null)
            {
                HttpCookie myCookie = new HttpCookie(clsUserAccount._CkValidKey);
                myCookie.Expires = DateTime.Now.AddDays(-1d);
                HttpContext.Current.Response.Cookies.Add(myCookie);
            }
        }

        public static void ChangePassword(string username, string newpassword)
        {
            DataTableManage SaveDTM = new DataTableManage();
            string sql = "UPDATE [tbl_UserAccount] SET [UserPass] = @UserPass WHERE UserName=@UserName";
            SaveDTM.Sql = sql;
            SaveDTM.AddNewParam("@UserPass", newpassword);
            SaveDTM.AddNewParam("@UserName", username);
            SaveDTM.Update();
        }

        public static void setUserLoginCookie(clsUserAccount usr)
        {
            HttpCookie myCookie = new HttpCookie(clsUserAccount._CkValidKey);
            myCookie["u"] = Utils.Encrypt(usr._username);
            myCookie["p"] = Utils.Encrypt(usr._userpass);
            //myCookie.Expires = DateTime.Now.AddDays(30d);
            HttpContext.Current.Response.Cookies.Add(myCookie);
        }


        public static clsUserAccount getCookieUser()
        {
            return getCookieUser(false);
        }

        public static clsUserAccount getCookieUser(bool valid)
        {

            string user = "", userpass = "";
            if (HttpContext.Current.Request.Cookies[clsUserAccount._CkValidKey] != null)
            {
                if (HttpContext.Current.Request.Cookies[clsUserAccount._CkValidKey]["u"] != null)
                {
                    user = Utils.Decrypt(HttpContext.Current.Request.Cookies[clsUserAccount._CkValidKey]["u"]);
                }
                if (HttpContext.Current.Request.Cookies[clsUserAccount._CkValidKey]["p"] != null)
                {
                    userpass = Utils.Decrypt(HttpContext.Current.Request.Cookies[clsUserAccount._CkValidKey]["p"]);
                }
            }

            clsUserAccount usr = null;
            if (user != "" && userpass != "")
            {
                if (valid)
                {
                    usr = clsUserAccount.ValidUser(user, userpass);
                }
                else
                {
                    usr = new clsUserAccount();
                    usr._username = user;
                    usr._userpass = userpass;
                }
            }
            else
            {
                usr = null;
            }
            return usr;
        }

        public void delFile(string oldPathFile)
        {
            string strRootPath = System.Web.HttpContext.Current.Server.MapPath("~/");
            strRootPath += "/" + oldPathFile;
            if (System.IO.File.Exists(strRootPath))
                System.IO.File.Delete(strRootPath);
        }

        public static clsUserAccount GetByKey(int prmUserID)
        {
            clsUserAccount entity = new clsUserAccount();
            DBase dbo = new DBase();
            System.Data.IDataReader dr = dbo.ExecuteReader("SELECT * FROM [tbl_UserAccount] WHERE UserID=" + prmUserID.ToString());
            if (dr.Read())
            {
                entity = DataReaderToEntity(dr);
            }
            dr.Dispose();
            dr = null;
            dbo.CloseConn();
            dbo = null;
            return entity;
        }

        private static clsUserAccount DataReaderToEntity(System.Data.IDataReader dr)
        {
            clsUserAccount entity = new clsUserAccount();

            int intTMP = 0;
            if (!int.TryParse(dr["UserID"].ToString(), out intTMP))
                intTMP = 0;
            entity._userid = intTMP;
            bool boolTMP = false;
            if (!bool.TryParse(dr["UserDisable"].ToString(), out boolTMP))
                boolTMP = false;
            entity._userdisable = boolTMP;
            DateTime datetimeTMP = new DateTime(1900, 1, 1);
            if (!DateTime.TryParse(dr["ExpireDate"].ToString(), out datetimeTMP))
                datetimeTMP = new DateTime(1900, 1, 1);
            entity._expiredate = datetimeTMP;
            entity._username = dr["UserName"].ToString();
            entity._userpass = dr["UserPass"].ToString();
            entity._usermail = dr["UserMail"].ToString();
            intTMP = 0;
            if (!int.TryParse(dr["MemberType"].ToString(), out intTMP))
                intTMP = 0;
            entity._membertype = intTMP;
            datetimeTMP = new DateTime(1900, 1, 1);
            if (!DateTime.TryParse(dr["AddDate"].ToString(), out datetimeTMP))
                datetimeTMP = new DateTime(1900, 1, 1);
            entity._adddate = datetimeTMP;
            datetimeTMP = new DateTime(1900, 1, 1);
            if (!DateTime.TryParse(dr["LastLogin"].ToString(), out datetimeTMP))
                datetimeTMP = new DateTime(1900, 1, 1);
            entity._lastlogin = datetimeTMP;
            entity._lastip = dr["LastIP"].ToString();
            intTMP = 0;
            if (!int.TryParse(dr["LoginTimes"].ToString(), out intTMP))
                intTMP = 0;
            entity._logintimes = intTMP;
            return entity;
        }

        #region 增删改数据库操作

        public static int Insert(clsUserAccount prmEntity)
        {
            DataTableManage SaveDTM = new DataTableManage();
            string sql;
            sql = string.Format("insert into [tbl_UserAccount](" +
                            " [UserName]," +
                            " [UserPass]," +
                            " [UserMail]," +
                            " [MemberType]," +
                            " [AddDate]," +
                            " [LastLogin]," +
                            " [LastIP]," +
                            " [LoginTimes]," +
                            " [UserDisable]," +
                            " [ExpireDate]" +
            ") values (" +
                    "@UserName," +
                    "@UserPass," +
                    "@UserMail," +
                    "@MemberType," +
                    "@AddDate," +
                    "@LastLogin," +
                    "@LastIP," +
                    "@LoginTimes," +
                    "@UserDisable," +
                    "@ExpireDate" +
            ")");
            SaveDTM.Sql = sql;
            SaveDTM.AddNewParam("@UserName", prmEntity._username);
            SaveDTM.AddNewParam("@UserPass", prmEntity._userpass);
            SaveDTM.AddNewParam("@UserMail", prmEntity._usermail);
            SaveDTM.AddNewParam("@MemberType", prmEntity._membertype);
            SaveDTM.AddNewParam("@AddDate", prmEntity._adddate);
            SaveDTM.AddNewParam("@LastLogin", prmEntity._lastlogin);
            SaveDTM.AddNewParam("@LastIP", prmEntity._lastip);
            SaveDTM.AddNewParam("@LoginTimes", prmEntity._logintimes);
            SaveDTM.AddNewParam("@UserDisable", prmEntity._userdisable);
            SaveDTM.AddNewParam("@ExpireDate", prmEntity._expiredate);
            int id = SaveDTM.InsertGetId();

            clsUserCompanyInfo com = new clsUserCompanyInfo();
            com.UserID = id;
            com.UserName = prmEntity._username;
            com.MemberType = prmEntity._membertype;
            clsUserCompanyInfo.Insert(com);

            return 1;
        }

        public static bool Delete(int prmUserID)
        {
            DBase dbo = new DBase();
            dbo.ExecSql(string.Format("DELETE FROM [tbl_UserAccount] WHERE UserID={0} delete from [tbl_usercompanyinfo] where userid={0}", prmUserID));
            dbo.CloseConn();
            dbo = null;
            return true;
        }

        public static bool Update(clsUserAccount prmEntity)
        {
            DataTableManage SaveDTM = new DataTableManage();
            string sql;
            sql = "UPDATE [tbl_UserAccount] SET " +
                "[UserName] = @UserName, " +
                "[UserPass] = @UserPass, " +
                "[UserMail] = @UserMail, " +
                "[MemberType] = @MemberType, " +
                "[AddDate] = @AddDate, " +
                "[LastLogin] = @LastLogin, " +
                "[LastIP] = @LastIP, " +
                "[LoginTimes] = @LoginTimes, " +
                "[UserDisable] = @UserDisable, " +
                "[ExpireDate] = @ExpireDate " +
            " WHERE UserID=@UserID";
            SaveDTM.Sql = sql;
            SaveDTM.AddNewParam("@UserName", prmEntity._username);
            SaveDTM.AddNewParam("@UserPass", prmEntity._userpass);
            SaveDTM.AddNewParam("@UserMail", prmEntity._usermail);
            SaveDTM.AddNewParam("@MemberType", prmEntity._membertype);
            SaveDTM.AddNewParam("@AddDate", prmEntity._adddate);
            SaveDTM.AddNewParam("@LastLogin", prmEntity._lastlogin);
            SaveDTM.AddNewParam("@LastIP", prmEntity._lastip);
            SaveDTM.AddNewParam("@LoginTimes", prmEntity._logintimes);
            SaveDTM.AddNewParam("@UserDisable", prmEntity._userdisable);
            SaveDTM.AddNewParam("@ExpireDate", prmEntity._expiredate);
            SaveDTM.AddNewParam("@UserID", prmEntity._userid);
            SaveDTM.Update();
            return true;
        }

        #endregion

        public static List<clsUserAccount> GetCollection()
        {
            return GetCollection(0);
        }

        public static List<clsUserAccount> GetCollection(int membertype)
        {
            string sql = "SELECT * FROM [tbl_UserAccount] ";

            if (membertype == 1)
                sql += " WHERE MemberType=1 ";
            else if (membertype == 2)
                sql += " WHERE MemberType=2 ";

            sql += " ORDER BY UserID DESC";

            return GetCollectionBySQL(sql);
        }

        private static List<clsUserAccount> GetCollectionBySQL(string sql)
        {
            List<clsUserAccount> ls = new List<clsUserAccount>();
            DBase dbo = new DBase();
            System.Data.IDataReader dr = dbo.ExecuteReader(sql);
            while (dr.Read())
            {
                ls.Add(DataReaderToEntity(dr));
            }
            dr.Dispose();
            dr = null;
            dbo.CloseConn();
            dbo = null;
            return ls;
        }


        #region 字段属性

        private int _userid = 0;
        /// <summary>
        /// 用户ID-自增
        /// </summary>
        public int UserID
        {
            get { return _userid; }
            set { _userid = value; }
        }

        private string _username = "";
        /// <summary>
        /// 用户名30位
        /// </summary>
        public string UserName
        {
            get { return _username; }
            set { _username = value; }
        }

        private string _userpass = "";
        /// <summary>
        /// 用户密码30位
        /// </summary>
        public string UserPass
        {
            get { return _userpass; }
            set { _userpass = value; }
        }

        private string _usermail = "";
        /// <summary>
        /// 邮箱
        /// </summary>
        public string UserMail
        {
            get { return _usermail; }
            set { _usermail = value; }
        }

        private int _membertype = 0;
        /// <summary>
        /// 用户类型：1-经销商用户，2-厂商用户
        /// </summary>
        public int MemberType
        {
            get { return _membertype; }
            set { _membertype = value; }
        }

        private DateTime _adddate = new DateTime(1900, 1, 1);
        /// <summary>
        /// 用户添加时间
        /// </summary>
        public DateTime AddDate
        {
            get { return _adddate; }
            set { _adddate = value; }
        }

        private DateTime _lastlogin = new DateTime(1900, 1, 1);
        /// <summary>
        /// 最后登陆时间
        /// </summary>
        public DateTime LastLogin
        {
            get { return _lastlogin; }
            set { _lastlogin = value; }
        }

        private string _lastip = "";
        /// <summary>
        /// 最后登入IP
        /// </summary>
        public string LastIP
        {
            get { return _lastip; }
            set { _lastip = value; }
        }

        private int _logintimes = 0;
        /// <summary>
        /// 总登陆次数
        /// </summary>
        public int LoginTimes
        {
            get { return _logintimes; }
            set { _logintimes = value; }
        }

        private bool _userdisable = false;
        /// <summary>
        /// 用户是否被禁止登入
        /// </summary>
        public bool UserDisable
        {
            get { return _userdisable; }
            set { _userdisable = value; }
        }

        private DateTime _expiredate = new DateTime(1900, 1, 1);
        /// <summary>
        /// 到期时间
        /// </summary>
        public DateTime ExpireDate
        {
            get { return _expiredate; }
            set { _expiredate = value; }
        }

        #endregion
    }
}
